package com.jsy.common.leetcode;

class WordDictionary {
    private boolean isEnd;
    private WordDictionary[] next;

    public WordDictionary() {
        next = new WordDictionary[26];
        isEnd = false;
    }
    
    public void addWord(String word) {
        WordDictionary cur = this;
        for (char c : word.toCharArray()) {
            if(cur.next[c - 'a'] == null){
                cur.next[c - 'a'] = new WordDictionary();
            }
            cur = cur.next[c - 'a'];
        }
        cur.isEnd = true;
    }

    public boolean search(String word) {
        return search(word,0,this);
    }
    public boolean search(String word,int index,WordDictionary cur) {
        if (index == word.length()){
            return cur.isEnd;
        }
        char c = word.charAt(index);
        if(c == '.'){
            for (WordDictionary next : cur.next) {
                if(next != null && next.search(word,index+1,next)){
                    return true;
                }
            }
        }else {
            if(cur.next[c - 'a']!= null && cur.next[c - 'a'].search(word,index+1,cur.next[c - 'a'])){
                return true;
            }
        }
        return false;
    }
}